import { DefaultRouter } from "../../router/routes";

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });
  return res;
}

const state = {
  routesMenu: [],
  IsShowFooter: true,
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    // 设置显示的路由菜单
    state.routesMenu = filterAsyncRoutes(routes, ["common"]);
  },
  SET_ISSHOWFOOTER: (state, bool) => {
    state.IsShowFooter = bool;
  },
};

const actions = {
  generateRoutes({ commit }) {
    commit("SET_ROUTES", DefaultRouter);
  },
  set_IsShowFooter({ commit }, bool) {
    commit("SET_ISSHOWFOOTER", bool);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
